package com.knife.blog.web.action;

import java.io.File;
import java.util.Date;

import org.apache.commons.fileupload.FileItem;
import com.knife.blog.domain.BlogTemplate;
import com.knife.blog.logic.BlogTemplateService;
import com.knife.blog.logic.ImgService;
import com.knife.blog.logic.impl.BlogTemplateServiceImpl;
import com.knife.blog.util.BlogFileUtil;
import com.knife.util.CommUtil;
import com.knife.web.Globals;
import com.knife.web.Module;
import com.knife.web.Page;
import com.knife.web.WebForm;
import com.knife.util.FileUtil;
import com.knife.web.tools.IActiveUser;
import com.knife.web.tools.IPageList;

public class BlogTemplateAction extends BaseCrudAction {
	
	private static BlogTemplateService blogTemplateService = BlogTemplateServiceImpl.getInstance();

	@Override
	public IPageList doQuery(WebForm form, int currentPage, int pageSize) {
		return blogTemplateService.queryTemplate(0,"",currentPage,pageSize);
	}
	
	public Page doUpload(WebForm form, Module module){
		return module.findPage("manageEdit");
	}
	
	public Page doManageList(WebForm form, Module module){
		IPageList pageList=blogTemplateService.queryTemplate(null, 1, 15);
		CommUtil.saveIPageList2WebForm(pageList, form);
		return module.findPage("manageList");
	}
	
	public Page doManageEdit(WebForm form, Module module){
		BlogTemplate blogTemplate=blogTemplateService.getBlogTemplate(form.get("cid").toString());
		form.addPo(blogTemplate);
		return module.findPage("manageEdit");
	}
	
    @Override
	public Page doAdd(WebForm form, Module module, IActiveUser user){
		BlogTemplate blogTemplate;
		/*if(blogTemplateService.getBlogTemplate((String)form.get("cid"))!=null){
			form.addResult("msg","模板名重复！");
			return module.findPage("edit");
		}*/
		blogTemplate = (BlogTemplate)form2Obj(form);
		//System.out.println((String)form.get("title"));
		blogTemplate.setTitle(form.get("title").toString());
		blogTemplate.setInputuser(user.getUserName());
		blogTemplate.setInputtime(new Date());
		blogTemplate.setStatus(new Integer(0));
		blogTemplate.setUpdated(Boolean.TRUE);
		FileItem templateFile = (FileItem)form.get("template");
		FileItem templateImg = (FileItem)form.get("img");
		if(templateFile==null){
			form.addResult("msg", "上传失败!");
			return module.findPage("manageEdit");
		}
		if(templateImg==null){
			form.addResult("msg", "上传失败!");
			return module.findPage("manageEdit");
		}
		String templateName = templateFile.getName();
		String imgName = templateImg.getName();
		if(!FileUtil.isAttacheFile(templateName)||!FileUtil.isImgageFile(imgName)){
			form.addResult("msg", "只能上传图片文件及压缩包文件！");
			return module.findPage("manageEdit");
		}else{
			String url = uploadFile(templateFile,Globals.APP_BASE_DIR+Globals.DEFAULT_TEMPLATE_PATH+"/blog/template/","file")[0];
			String[] arrayUrl = uploadFile(templateImg,Globals.APP_BASE_DIR+"upfile/blog/template/","img");
			String imgUrl = arrayUrl[0];
			String sImgUrl = arrayUrl[1];
			blogTemplate.setUrl(url);
			blogTemplate.setImg_url(imgUrl);
			blogTemplate.setS_img_url(sImgUrl);
			
			//上传之后解压
			url=Globals.APP_BASE_DIR+url;
			String outputDirectory = url.substring(0, url.lastIndexOf("/"));
            boolean ret = new BlogFileUtil().unZip(url, outputDirectory);
            if (ret) {
            	blogTemplate.setUpdated(Boolean.FALSE);
            }
		}
		boolean ret = blogTemplateService.addTemplate(blogTemplate);
		if(ret){
			form.addResult("msg", "添加成功!");
			form.addResult("close","关闭！");
			return doManageList(form,module);
			//return module.findPage("edit");			
		}else{
			form.addResult("msg", "添加失败!");
			return module.findPage("manageEdit");
		}
	}
    @Override
	public Page doDel(WebForm form, Module module, IActiveUser user){
		String cid = (String)form.get("cid");
		//BlogTemplate blogtemp=blogTemplateService.getBlogTemplate(cid);
		//deleFile(blogtemp.getUrl());
		boolean ret = blogTemplateService.delTemplate(cid);		
		form.addResult("msg", ret ? "删除成功!" : "删除失败!");
		if(user.getUserName().equals("admin")){
			return doManageList(form,module);			
		}
		else{
		return super.doQuery(form, module, user);
		}
	}
	public void deleFile(String filename){
		
		String a=Globals.DEFAULT_TEMPLATE_PATH;
		System.out.println(a);
	}
	
	public String[] uploadFile(FileItem fileItem,String filePath,String type) {
		String[] ret = new String[2];
		String clientName = fileItem.getName();
		FileUtil.isImgageFile(clientName);
		if (fileItem != null) {
			/*String filePath = Globals.DEFAULT_TEMPLATE_PATH + "/blog/template"
					+ blog.getCid() + "/";*/
			File fdir = new File(filePath);
			if (!fdir.exists())
				fdir.mkdirs();
			try {
				String fileName;
				if(type.equals("file")){
					fileName = clientName.substring(clientName.lastIndexOf(File.separator) + 1);
				}else{
					fileName = (clientName.substring(clientName.lastIndexOf(File.separator) + 1)).split("\\.")[1];
					fileName = CommUtil.getRandString(8)+"."+fileName;
				}
				File file = new File(filePath + fileName);
				if(file.exists()){
					file.delete();
				}
				fileItem.write(file);
				if(type.equals("file"))
					ret[0] = Globals.DEFAULT_TEMPLATE_PATH + "/blog/template/" + fileName;
				if(type.equals("img")){
					ret[0] = "/upfile/blog/template/" + fileName;
					String s_fileName = "s_"+fileName;
					String s_url = "/upfile/blog/template/" + s_fileName;
					ImgService is = new ImgService(filePath, filePath, fileName, s_fileName);
					if(is.CreateThumbnail(120,90))
						ret[1] = s_url;
					else
						ret = null;
				}
				System.out.println("BlogTemplateAction:"+ret[0]);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return ret;
	}

	@Override
	public Object form2Obj(WebForm form) {
		String cid = CommUtil.null2String(form.get("cid"));
		BlogTemplate obj = blogTemplateService.getBlogTemplate(cid);
		if (obj == null)
			obj = new BlogTemplate();
		// 此处需要修改，妨止系统字段被从外面非法赋值
		form.toPo(obj);
		return obj;
	}

}
